//
//  ZWUserAccountViewModel.swift
//  张伟的微博
//
//  Created by 伟 on 16/2/29.
//  Copyright © 2016年 伟. All rights reserved.
//

import UIKit

class ZWUserAccountViewModel: NSObject {
    
        //  MVM
    static let sharedInstance: ZWUserAccountViewModel = ZWUserAccountViewModel()
    
    var userAccount :ZWUserAccount?
    
    
    private override init(){
        super.init()
        userAccount = loadUserAccount()
        
    }
    func loadAccessToken(code: String,accessTokendidFinIshed:(error:NSError?) ->()){
        ZWNetWorwTool.sharedInstance.getAccesstoken(code, accessTokenFinished: { (response, error) -> () in
            if response == nil || error != nil {
                
                accessTokendidFinIshed(error: error!)
                return
            }
            print("AccessToken获得成功\(response)")
            
            self.userAccount = ZWUserAccount(dict: response!)
            //将模型保存到沙盒
            self.saveUserAccount()
            return accessTokendidFinIshed(error: nil)
            
        })
    
    }
    
    
    let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/Account.plist")
    func saveUserAccount(){
        if userAccount != nil {
           
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath!)//toFile:沙河路径
        }
    }

    //解档
    private func loadUserAccount ()->ZWUserAccount?{

      let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath!) as? ZWUserAccount
        //NSdate()显示当前时间
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("account没有过期~")
            return account
        }else {
        return nil
        }
    }
    
    var userLodin: Bool {
    
        return userAccount != nil
    }
    //获取用户信息
    func loadUserInfo(loadUserInfoCallBack: (error:NSError?)->()) {
        ZWNetWorwTool.sharedInstance.loadUserInfo { (result, error) -> () in
            if result == nil || error != nil {
                //授权出错
                loadUserInfoCallBack(error: error!)
                return
            }
            print("拿到了用户的数据")
            self.userAccount?.screen_name = result?["screen_name"] as? String
            self.userAccount?.avatar_large = result?["avatar_large"] as? String
            //保存数据
            self.saveUserAccount()
            //执行闭包
            loadUserInfoCallBack(error: nil)
            
        }
        
    }
    
}
